package com.bodystm.server;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.web.HttpRequestHandler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.AttributeKey;

public class WebSocketServerHandler  extends SimpleChannelInboundHandler<Object> {
	@SuppressWarnings("unused")  
    private static final Logger logger = Logger.getLogger(WebSocketServerHandler.class);  
      
    private IWebSocketService websocketService;  
      
    private IHttpService httpService;  
  
    public WebSocketServerHandler(IWebSocketService websocketService, IHttpService httpService) {  
        super();  
        this.websocketService = websocketService;  
        this.httpService = httpService;  
    }  
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
            ctx.pipeline().remove(ChannelHandler.class);
            // group.writeAndFlush("");
            //group.add(ctx.channel());
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
    /* 
     * @see 
     * io.netty.channel.SimpleChannelInboundHandler#channelRead0(io.netty.channel 
     * .ChannelHandlerContext, java.lang.Object) 
     */  
    @Override  
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {  
        if (msg instanceof FullHttpRequest) {  
            httpService.handleHttpRequest(ctx, (FullHttpRequest) msg);  
        } else if (msg instanceof WebSocketFrame) {  
            websocketService.handleFrame(ctx, (WebSocketFrame) msg);  
        }  
    }  
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }
      
    /*  
     * @see io.netty.channel.ChannelInboundHandlerAdapter#channelReadComplete(io.netty.channel.ChannelHandlerContext) 
     */  
    @Override  
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {  
        ctx.flush();  
    } 
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
        Channel incoming = ctx.channel();
        String userId = (String) incoming.attr(AttributeKey.valueOf(incoming.id().asShortText())).get();
//        UserIdToWebSocketChannelShare.userIdToWebSocketChannelMap.remove(userId);// 删除缓存的通道
//        loginTimeService.outLine(userId, new Date());// 下线通过
    }
}
